package com.nf.health.app.homepage.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.domain.EaseUser;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.LoadWebActivty2;
import com.nf.health.app.activity.miansearch.MainSearchDocActivity2;
import com.nf.health.app.activity.my.HousePersionKnowledgeMianActivity;
import com.nf.health.app.activity.my.impl.MyContact;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.fragment.NoIBaseFragment;
import com.nf.health.app.homepage.adapter.HomePageAdapter;
import com.nf.health.app.http.Act;
import com.nf.health.app.impl.event.EventContact;
import com.nf.health.app.impl.event.EventType;
import com.nf.health.app.models.BannerBean;
import com.nf.health.app.models.HealthManagerStatus;
import com.nf.health.app.models.HealthNewsBean;
import com.nf.health.app.models.HealthStateInfo;
import com.nf.health.app.models.HousePersionCompeteModel;
import com.nf.health.app.models.MengHistoryModel;
import com.nf.health.app.models.RedpacketBean;
import com.nf.health.app.models.SchemeBean;
import com.nf.health.app.models.SolutionSchemeBean;
import com.nf.health.app.models.TestPlan;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ColorUtil;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.LocationUtil;
import com.nf.health.app.utils.NetUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.DialogActivity;
import com.nf.health.app.widget.MyMainItemAnimation;
import com.nf.health.app.widget.ShowCommentDialog;
import com.nf.health.app.widget.ShowDialogFactory;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Jason on 2016/3/16.
 */
public class MainNewHomeFragment extends NoIBaseFragment implements View.OnClickListener {
    private static final String FLAG_HEALTH_DETAIL = "flag_health_detail";
    private static final String FLAG_ADS = "flagAds";////广告位
    private static final String FLAG_PLAN = "flagPlan";////计划
    private static final String FLAG_STATE = "flagstate";////计划
    private static final String FLAG_HEALT_NEWS = "flagHealthNews";// 功能入口
    // private static final String FLAG_HEALT_STATE = "flagHealthState";
    private static final String FLAG_HEALTH_PLAN = "flagHealthPlan";

    private final String REQUEST_GETTOPIMAGES = "public.share.getTopImages.action";
    private String REQUEST_GETTOPIMAGES_CHECK = "updateTodayTime.check";
    /********
     * 健康资讯的数据
     ***********/
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;

    HomePageAdapter homePageAdapter;

    @Bind(R.id.ll_title_layout)
    LinearLayout ll_title_layout;
    @Bind(R.id.ll_search_doc)
    LinearLayout ll_search_doc;
    @Bind(R.id.tv_search_doc)
    TextView tv_search_doc;

    @Bind(R.id.iv_search_white)
    ImageView iv_search_white;
    @Bind(R.id.iv_float_hourse_persion)
    ImageView iv_float_hourse_persion;
    @Bind(R.id.iv_grap_red_packa)
    ImageView iv_grap_red_packa;
    @Bind(R.id.iv_search_black)
    ImageView iv_search_black;
    Bitmap bm;
    private ShowDialogFactory dialogFactory;
    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constants.DESCRIPTOR);


    private  ShowCommentDialog showCommentDialog;
    HealthStateInfo healthStateInfo;
    private int mDistanceY;
    private boolean isfirstPer;//是否第一次执行监听方法
    HousePersionCompeteModel housePersionCompeteModel = null;//当前的知识问答
    private String hpuid = "0";
    private String mProvinceS;
    private String mCityS;
    private String mDistrictS;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_main_home_recycleview);
        ButterKnife.bind(this, getView());
        EventBus.getDefault().register(this);
        initView();
        initMyLocation();
        String yindao = PreferenceHelper.getString(PreferenceHelper.DATAYINDAO, "");
        if (TextUtils.isEmpty(yindao)) {
            initTipDialog();//显示引导图片
        }

        bm = BitmapFactory.decodeResource(getResources(), R.drawable.data_scancode);//扫一扫加关注

        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new MyMainItemAnimation());


        homePageAdapter = new HomePageAdapter(getActivity(), healthStateInfo);
        recyclerView.setAdapter(homePageAdapter);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                if (NetUtil.isNetworkAvailable(getActivity())) {

                }else{
                    GetToast.useString(getActivity(), getString(R.string.l_no_connect_err));
                }
                initData(true);
            }
        });
        initListener();

    }

    private void initView() {
        iv_float_hourse_persion.setVisibility(View.INVISIBLE);
        ll_search_doc.setOnClickListener(this);
        iv_grap_red_packa.setOnClickListener(this);
        iv_float_hourse_persion.setOnClickListener(this);
        ll_title_layout.setBackgroundColor(Color.TRANSPARENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int statusBarHeight = ScreentUtils.getStatusBarHeight(getActivity().getBaseContext());
            ll_title_layout.setPadding(0, statusBarHeight + 10, 0, 10);
        } else {
            ll_title_layout.setPadding(0, 20, 0, 20);
        }
    }

    private void initListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (isfirstPer) {
                    //滑动的距离
                    mDistanceY += dy;

                    int titleHeight = ll_title_layout.getBottom();

                    //当滑动的距离 <= 标题栏高度的时候，改变标题栏背景色的透明度，达到渐变的效果
                    if (mDistanceY <= titleHeight) {
                        float scale = (float) mDistanceY / titleHeight; //[0,1]
                        //ll_title_layout.setBackgroundColor(Color.argb((int) alpha, 46, 134, 244));
                        ll_title_layout.setBackgroundColor((int) ColorUtil.evaluateColor(scale, 0x002E86F4, 0xFF2E86F4));
                        if (mDistanceY == 0) {
                            ll_title_layout.setBackgroundResource(R.color.transparent);
                        }
                    } else {
                        //上述虽然判断了滑动距离与标题栏高度相等的情况，但是实际测试时发现，标题栏的背景色
                        //很少能达到完全不透明的情况，所以这里又判断了滑动距离大于标题栏高度的情况，
                        //将标题栏的颜色设置为完全不透明状态
                        ll_title_layout.setBackgroundResource(R.color.theme_color);
                    }
                }
                isfirstPer = true;
            }
        });
    }


    public void onResume() {
        super.onResume();
        if (NetUtil.isNetworkAvailable(getActivity())) {
            provider.requestHealthStateDetail(FLAG_HEALTH_DETAIL);//请求总的数据
            initData(true);
        } else {
            GetToast.useString(getActivity(), getString(R.string.l_no_connect_err));
        }
        hpuid = PreferenceHelper.getString(PreferenceHelper.TYPE_HPID, "0");

        //provider.requestAds(mProvinceS, mCityS, mDistrictS,FLAG_ADS);
    }


    public void initData(boolean isFreah) {
        provider.requestAddScore("2", "");//添加积分
//        provider.requestAds(mProvinceS, mCityS, mDistrictS,FLAG_ADS);
        provider.requestPlan(hpuid, FLAG_PLAN);//测量计划
        provider.getInterveneIndex(hpuid);//获取解决方案
        provider.hourseClearTakeCompete();//问卷答题哦
        provider.requestHomeState(FLAG_STATE);//获取健康团队解决状态
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        if (swipeRefreshLayout != null) {
            if (!swipeRefreshLayout.isRefreshing()) {
                showLoading();
            }
        }
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        homePageAdapter.setAutoScroll(true);
    }

    @Override
    public void onStop() {
        super.onStop();
        homePageAdapter.setAutoScroll(false);
    }


    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (FLAG_ADS.equals(actionName)) { /********广告位***： recycleView Hodler 的position为0*******/
            ArrayList<BannerBean> bannerBeans = (ArrayList<BannerBean>) object;
            //adsPagerAdapter = new AdsPagerAdapter(getActivity(), bannerBeans);
            //homePageAdapter.setAdsPagerAdapter(adsPagerAdapter);
            homePageAdapter.setBannerDatas(bannerBeans);
            //provider.requestHealthState(FLAG_HEALT_STATE);
            provider.getomeActivityIndexOnsale();//首页活动
        } else if (FLAG_PLAN.equals(actionName)) { /********测量计划***： recycleView Hodler 的position为0*******/

            String list = JsonUtils.getFiledData(object + "", "list");
            String hpuid = JsonUtils.getFiledData(object + "", "hpuid");
            Gson gson = new MyGsonBuilder().createGson();
            List<TestPlan> beans = gson.fromJson(list, new TypeToken<List<TestPlan>>() {
            }.getType());
            PreferenceHelper.putString(PreferenceHelper.TYPE_HPID,hpuid);//请求出当前健康包id  就存储
            ArrayList<TestPlan> bannerBeans = (ArrayList<TestPlan>) beans;
            homePageAdapter.setTestPlan(bannerBeans, hpuid);
        } else if (FLAG_STATE.equals(actionName)) { /********获取点击状态***：健康管理团队 recycleView Hodler 的position为0*******/
            HealthManagerStatus state = (HealthManagerStatus) object;
            //  红包状态 红包状态 1不显示,2显示
            String status2 = state.getRedState();
            if (!TextUtils.isEmpty(status2)) {
                if ("1".equals(status2)) {
                    iv_grap_red_packa.setVisibility(View.GONE);
                } else if ("2".equals(status2)) {
                    iv_grap_red_packa.setVisibility(View.VISIBLE);
                    ViewUtil.doWaggleAnimation(iv_grap_red_packa);
                }
            }
            homePageAdapter.setHealthManagerStatus(state);
           // DbManager.getInstance().saveContact(state.getDoctorname(),state.getDoctorname(),state.getDoctorimg());//保存一个联系人
            EaseUser ease = new EaseUser(state.getDoctorid());
            ease.setNick(state.getDoctorname());
            ease.setAvatar(state.getDoctorimg());
            DbManager.getInstance().saveContact(ease);
        } else if (FLAG_HEALT_NEWS.equals(actionName)) {/********健康资讯的数据*recycleView Hodler 的position为3**********/
            HealthNewsBean healthNewsBean = (HealthNewsBean) object;
            homePageAdapter.setHealthNews(healthNewsBean);

        } else if (FLAG_HEALTH_PLAN.equals(actionName)) {  /*******健康/健康  方案计划带头部**recycleView Hodler 的position为2******/
            List<SchemeBean> schemeBeans = (List<SchemeBean>) object;
            homePageAdapter.setHealthPlan(schemeBeans);
            provider.requestHealthNews(FLAG_HEALT_NEWS);
            //} else if (FLAG_HEALT_STATE.equals(actionName)) {/********功能入口： 健康状态，查找医生，快速问诊，recycleView Hodler 的position为1********/
           /* HealthStateBean healthStateBean = (HealthStateBean) object;
            homePageAdapter.setHealthState(healthStateBean);*/
        } else if (FLAG_HEALTH_DETAIL.equals(actionName)) {  /*******请求总的数据********/
            healthStateInfo = (HealthStateInfo) object;
            if (homePageAdapter == null) {
                homePageAdapter = new HomePageAdapter(getActivity(), healthStateInfo);
                recyclerView.setAdapter(homePageAdapter);
            } else {
                homePageAdapter.setMyNotifyChanged(healthStateInfo);
            }
        } else if (Act.Flag.GET_INTERVENE_INDEX.equals(actionName)) {//解决方案 2016/11/23增加
            List<SolutionSchemeBean> list = (List<SolutionSchemeBean>) object;
            if (homePageAdapter != null) {
                homePageAdapter.setHomeSolution(list);
            }
        } else if (Act.Flag.FLAG_HOURSE_RESPONSIBLE_TAKE_COMPETE.equals(actionName)) {//健康明白人知识大赛
            housePersionCompeteModel = (HousePersionCompeteModel) object;
            if (housePersionCompeteModel != null) {
                if (!TextUtils.isEmpty(housePersionCompeteModel.getPFlag()) && housePersionCompeteModel.getPFlag().equals("1")) {
                    iv_float_hourse_persion.setVisibility(View.VISIBLE);
                } else {
                    iv_float_hourse_persion.setVisibility(View.GONE);
                }
            }
        } else if (Act.Flag.FLAG_GET_HOME_ACTIVITY_INDEX_ONSALE.equals(actionName)) { /*******医生服务列表********/
            ArrayList<MengHistoryModel> list = (ArrayList<MengHistoryModel>) object;
            homePageAdapter.setListMengHistoryModel(list);
            provider.requestHealthPlan(FLAG_HEALTH_PLAN);
        } else if (Act.Flag.FLAG_QIANG_HONGBAO.equals(actionName)) { /*******抢红包********/
            RedpacketBean redpacketBean = (RedpacketBean) object;
            Intent intent = new Intent(getActivity(), DialogActivity.class);
            intent.putExtra("count", redpacketBean.getHealthycoin());
            intent.putExtra("url", redpacketBean.getUrl());
            startActivity(intent);
            if(showCommentDialog != null && showCommentDialog.isShowing()){
                showCommentDialog.dismissDialog();
            }
        }else if (actionName.equals(REQUEST_GETTOPIMAGES)) {
            // data.put("himg", "http://mbank.nf1000.com/img/app/zc7.png");//弹窗图片
            // data.put("url",  "www.baidu.com");//弹窗跳转地址
            // data.put("flag", "1");//0不弹窗，1弹窗
            // data.put("type", "1");//0每天一次弹窗，1每次打开弹窗
            JSONObject json = null;
            try {
                json = new JSONObject(object.toString());
                String himg = json.optString("himg");
                final String url = json.optString("url");
                String flag = json.optString("flag");
                String type = json.optString("type");
                final String title = json.optString("title");
                if (Integer.parseInt(flag) == 1) {//弹窗
                    if (Integer.parseInt(type) == 1) {//每次打开弹窗
                        if(dialogFactory == null) {
                            dialogFactory = new ShowDialogFactory(getActivity());
                            dialogFactory.setCancelable(false);
                            dialogFactory.setImageBitmapResouble(himg);
                            dialogFactory.setDdalog_Imgentry(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("url", url);
                                    bundle.putString("title", title);
                                    ActivityUtils.showActivity(getActivity(), LoadWebActivty2.class, bundle);
                                    dialogFactory.dismiss();
                                }
                            });
                            dialogFactory.setDdalog_entry(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialogFactory.dismiss();
                                }
                            });
                        }
                        if(!getActivity().isFinishing() && !dialogFactory.isShowing()){
                            dialogFactory.show();
                        }
                    } else if (Integer.parseInt(type) == 0) {//每天一次弹窗
                        setShowDayOneTime(himg, url, title);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void mainOnThreadRefreshUi(EventType eventType) {
        int type = eventType.getType();
        switch (type) {
            case EventContact.QUESTION_ADK://答题完毕刷新
                provider.hourseClearTakeCompete();//问卷答题哦
                break;
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        if (FLAG_ADS.equals(actionName)) {
            //provider.requestHealthState(FLAG_HEALT_STATE);
            provider.getomeActivityIndexOnsale();//首页活动
        } else if (FLAG_HEALT_NEWS.equals(actionName)) {

        } else if (FLAG_HEALTH_PLAN.equals(actionName)) {
            provider.requestHealthNews(FLAG_HEALT_NEWS);
        } else if (Act.Flag.FLAG_GET_HOME_ACTIVITY_INDEX_ONSALE.equals(actionName)) {
            provider.requestHealthPlan(FLAG_HEALTH_PLAN);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void initTipDialog() { // 初始化弹出框数据
        // TODO Auto-generated method stub

        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.activity_data_dialog9);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image6);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                initTipDialog2();
            }
        });
        dialog.show();

//        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
//        dialog.setContentView(R.layout.activity_data_dialog);
//        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image);
//        iv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//                initTipDialog4();
//            }
//        });
//        dialog.show();

    }

    private void initTipDialog2() { // 初始化弹出框消息
        // TODO Auto-generated method stub
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.activity_data_dialog2);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image2);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                initTipDialog3();
                //
            }
        });
        dialog.show();
    }

    private void initTipDialog3() { // 初始化弹出框快速问诊
        // TODO Auto-generated method stub
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.activity_data_dialog3);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image3);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                PreferenceHelper.putString(PreferenceHelper.DATAYINDAO, "1");
                initTipDialog4();
            }
        });
        dialog.show();
    }

    private void initTipDialog4() { // 初始化弹出框健康状态
        // TODO Auto-generated method stub
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.activity_data_dialog4);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image4);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                initTipDialog5();
            }
        });
        dialog.show();
    }

    private void initTipDialog5() { // 初始化弹出框健康自测.不用了2016/10/24
        // TODO Auto-generated method stub
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.activity_data_dialog5);
        ImageView iv = (ImageView) dialog.findViewById(R.id.forum_image5);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_search_doc://主界面进行搜索
                ActivityUtils.showActivity(getActivity(), MainSearchDocActivity2.class);//DocDetailActivity
                break;
            case R.id.iv_float_hourse_persion://健康明白人知识大赛
                if (housePersionCompeteModel != null) {
                    Bundle bundlePrivacy = new Bundle();
                    bundlePrivacy.putSerializable(MyContact.WEB_TO_SENSD_FLAG, housePersionCompeteModel);
                    ActivityUtils.showActivity(getActivity(), HousePersionKnowledgeMianActivity.class, bundlePrivacy);
                }
                break;
            case R.id.iv_grap_red_packa://抢红包
                showDialog();
                break;
        }
    }

    private void showDialog() {
         if(showCommentDialog == null) {
             showCommentDialog = new ShowCommentDialog(getActivity())
                     .createRedPackageDialog(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             provider.getRedpacket();//抢红包
                         }
                     });
         }
        if(showCommentDialog != null && !showCommentDialog.isShowing() && !getActivity().isFinishing()){
            showCommentDialog.showDialog();
        }
    }


    /**
     * 初始化定位及回调
     */
    public void  initMyLocation() {

        //省
        mProvinceS = PreferenceHelper.getProvince();
        //市
        mCityS = PreferenceHelper.getCity();
        //区
        mDistrictS = PreferenceHelper.getDistrict();
        provider.requestAds(mProvinceS, mCityS, mDistrictS,FLAG_ADS);
        LocationUtil.initial(getActivity(), new LocationUtil.CallAddress() {
            @Override
            public void addressInfo(String province, String city, String district) {
                String isFirstOpenApp = PreferenceHelper.getString(PreferenceHelper.DATAYINDAO, "");
                if(Util.isLogin()){//如果第一次运行App 广告弹窗要在引导页消失后再弹出
                    if(!TextUtils.isEmpty(isFirstOpenApp)) {
                        //广告弹窗
                        provider.getTopImages(province, city, district, REQUEST_GETTOPIMAGES);
                    }
                }
                //判断新定位到的位置信息和旧的是否一致
                if(mProvinceS.equals(province) && mCityS.equals(city) && mDistrictS.equals(district)){

                }else{
                    mProvinceS = PreferenceHelper.getProvince();
                    mCityS = PreferenceHelper.getCity();
                    mDistrictS = PreferenceHelper.getDistrict();
                    //加载数据并保存新定位的位置信息
                   provider.requestAds(mProvinceS, mCityS, mDistrictS,FLAG_ADS);
                    PreferenceHelper.saveLocation(province,city,district);
                }

            }

            @Override
            public void complete(double latitude, double longitude, String adress) {


            }

            @Override
            public void callRemainQuestFaild() {
                provider.getTopImages(mProvinceS, mCityS, mDistrictS,REQUEST_GETTOPIMAGES);
            }


        });
    }

    private void setShowDayOneTime(String himg, final String url, final String title) {
        Time t = new Time();
        t.setToNow();
        final String str = t.year + "年" + (t.month + 1) + "月" + t.monthDay + "日";
        final String nowtime = PreferenceHelper.getString(REQUEST_GETTOPIMAGES_CHECK, "");
        if (!nowtime.equals(str)) {
            if(dialogFactory == null){
                dialogFactory = new ShowDialogFactory(getActivity());
                dialogFactory.setCancelable(false);
                dialogFactory.setImageBitmapResouble(himg);
                dialogFactory.setDdalog_Imgentry(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", url);
                        bundle.putString("title", title);
                        ActivityUtils.showActivity(getActivity(), LoadWebActivty2.class, bundle);
                        dialogFactory.dismiss();
                    }
                });
                dialogFactory.setDdalog_entry(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogFactory.dismiss();
                    }
                });
            }
            if(!getActivity().isFinishing() && !dialogFactory.isShowing()){
                dialogFactory.show();
            }
            PreferenceHelper.putString(REQUEST_GETTOPIMAGES_CHECK, str);
        }
    }
}